<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/12 11:12
 * Blog：www.myblogs.xyz
 */

namespace app\admin\controller;


use think\facade\View;

class Vehicle extends Common
{
    public function index()
    {
        $this->vehicleList();
        return View::fetch('vehicle_list');
    }

    // 回收站
    public function recycle()
    {
        $this->vehicleList(3);
        return View::fetch('vehicle_list');
    }

    // 超时车
    public function overtime()
    {
        $this->vehicleList(4);
        return View::fetch('vehicle_list');
    }

    // 选择车辆信息
    public function selectVehicle()
    {
        $this->vehicleList();
        return View::fetch();
    }

    // 查看车辆
    public function looksVehicle()
    {
        $admin_id = input('param.admin_id', 0, 'intval');
        if (empty($admin_id)){
            $this->redirect(url('Admin/index', ['p'=>$this->p]));
        }
        $this->vehicleList(0, $admin_id);
        return View::fetch('vehicle_list');
    }

    protected function vehicleList($status = 0, $admin_id = 0)
    {
        $keywords = input('param.keywords');
        $area_id = input('param.area_id', 0, 'intval');
        $type_id = input('param.type_id', 0, 'intval');
        $is_binding = input('param.is_binding', 0, 'intval');
        $low_voltage = input('param.low_voltage', 0, 'intval');
        $is_overtime = input('param.is_overtime', 0, 'intval');
        $vehicle_status = input('param.status', 0, 'intval');
        $status_id = input('param.status_id', 0, 'intval');
        $list_where = [];
        if (!empty($keywords)){
            $list_where['number|device'] = $keywords;
        }
        if (!empty($admin_id)){
            $list_where['admin_id'] = $admin_id;
        }else{
            if ($this->adminId != 1){
                $list_where['admin_id'] = $this->adminId;
                $list_where['area_id'] = ['in', $this->adminData['area_ids']];
            }
        }
        if (!empty($status)){
            if ($status == 3){
                $list_where['state'] = 3;
            }else{
                $cur_time = time();
                $last_time = $cur_time - (3600*36);
                $list_where['state'] = ['lt', 3];
                $list_where['last_time'] = ['lt', $last_time];
            }
        }
        $state = input('param.state', 0, 'intval');
        if (!empty($state)){
            $list_where['state'] = $state;
        }
        if (!empty($this->area_id)){
            $list_where['area_id'] = $this->area_id;
        }else{
            if (!empty($area_id)){
                $list_where['area_id'] = $area_id;
            }
        }
        if (!empty($type_id)){
            $list_where['type_id'] = $type_id;
        }
        // 是否绑定
        if (!empty($is_binding)){
            $list_where['is_binding'] = $is_binding;
        }
        // 查询低电压车辆
        if (!empty($low_voltage)){
            $list_where['state'] = 1;
            $list_where['low_voltage'] = $low_voltage - 1;
        }
        $last_time = NEW_TIME - (3600 * 24);
        // 24小时未骑车辆
        if ($is_overtime == 1){
            $list_where['state'] = 1;
            $list_where['status'] = 0;
            $list_where['last_time'] = ['lt', $last_time];
        }
        // 24小时未还车辆
        if ($is_overtime == 2){
            $list_where['state'] = 1;
            $list_where['status'] = ['in', '1,2'];
            $list_where['last_time'] = ['lt', $last_time];
        }
        // 获取故障车信息
        if (!empty($vehicle_status)){
            $list_where['status'] = $vehicle_status;
        }
        // 获取车辆状态
        $order_str = 'number asc,create_time asc,vehicle_id asc';
        $vehicle_model =  new \app\common\model\Vehicle();
        $data = $vehicle_model->vehicleLists($list_where, 10, $order_str);
        // 是否显示下载
        $no_code = $vehicle_model->where(['state'=>2,'qr_code'=>''])->count();
        // 是否现在显示下载
        $is_download = 0;
        $file_path = getcwd() . '/static/upload/code/' . date('Y/m/d');
        if (is_dir($file_path)) {
            $is_download = 1;
        }
        // 设备类型
        $device_type = new \app\common\model\DeviceType();
        $type_list = $device_type->getList(['is_open'=>1,'type_id'=>['neq', 4]]);
        // 获取当前账户区域
        $area_where['area_pid'] = ['neq', 0];
        if ($this->adminData['level'] != 0){
            $area_where['manager_id'] = $this->adminId;
            if ($this->adminData['level'] == 1){
                if ($this->adminData['role_id'] != 2){
                    $area_where['manager_id'] = $this->adminData['admin_pid'];
                }
            }
        }
        $area_model = new \app\common\model\Area();
        $area_list = $area_model->getList($area_where);

        View::assign([
            'state'=>$state,
            'status'=>$status,
            'no_code'=>$no_code,
            'area_id'=>$area_id,
            'type_id'=>$type_id,
            'type_list'=>$type_list,
            'area_list'=>$area_list,
            'is_download'=>$is_download,
            'keywords'=>$keywords,
            'status_id'=>$status_id,
            'is_binding'=>$is_binding,
            'count'=>$data['count'],
            'list'=>$data['list'],
            'page'=>$data['page'],
        ]);
    }

    public function insertVehicle()
    {
        $this->saveVehicle();
        return View::fetch('save_vehicle');
    }

    public function updateVehicle()
    {
        $this->saveVehicle();
        return View::fetch('save_vehicle');
    }

    protected function saveVehicle()
    {
        $area_model = new \app\common\model\Area();
        $vehicle_model = new \app\common\model\Vehicle();
        if (request()->isPost())
        {
            $data = input('post.');
            // 获取扫码下载地址
            $setting_model = new \app\common\model\Setting();
            $setting_data = $setting_model->settingFind('site');
            if (empty($setting_data['scan_url'])){
                $this->returnError('请设置扫码下载地址');
            }
            $data['is_binding'] = 0;
            if (!empty($data['device'])){
                // 检测设备是否存在
                if (empty($data[$vehicle_model->getPk()])){
                    if ($vehicle_model->getExists(['device'=>$data['device']])){
                        $this->returnError('该设备已存在');
                    }
                }else{
                    if ($vehicle_model->getExists(['device'=>$data['device'], 'vehicle_id'=>['neq', $data['vehicle_id']]])){
                        $this->returnError('该设备已存在');
                    }
                }
                $data['is_binding'] = 1;
            }
            if (!empty($data['area_id'])){
                // 获取区域信息
                $area_data = $area_model->getFind($data['area_id'], 'area_id,admin_id');
                if (!empty($area_data)){
                    $data['area_id'] = $area_data['area_id'];
                    $data['admin_id'] = $area_data['admin_id'];
                }else{
                    $data['area_id'] = '';
                    $data['admin_id'] = '';
                }
            }
            if ($this->adminData['level'] != 0){
                $area_where['area_pid'] = ['neq', 0];
                $area_where['manager_id'] = $this->adminId;
                if ($this->adminData['level'] == 1){
                    if ($this->adminData['role_id'] != 2){
                        $area_where['manager_id'] = $this->adminData['admin_pid'];
                    }
                }
                $area_data = $area_model->getFind($area_where, 'area_id,manager_id');
                if (!empty($area_data)){
                    $data['area_id'] = $area_data['area_id'];
                    $data['admin_id'] = $area_data['manager_id'];
                }else{
                    $data['area_id'] = '';
                    $data['admin_id'] = '';
                }
            }
            if (empty($data[$vehicle_model->getPk()])){
                $curr_number = $vehicle_model->vehicleNumber($data['type_id']);
                if (!$curr_number){
                    $this->returnError('每月添加设备数量不能超过9999台');
                }
                $data['number'] = $curr_number;
                $data['password'] = empty($data['password'])? '123456' : $data['password'];
                $data['create_time'] = NEW_TIME;
                $data['last_time'] = NEW_TIME;
                $rows = $vehicle_model->operation($data, true, false, true);
                if (empty($rows)){
                    $this->returnError($vehicle_model->getError());
                }
                $data['vehicle_id'] = $rows;
            }
            $data['update_time'] = NEW_TIME;
            $data['state'] = 2;
            // 获取车辆信息
            $vehicle_data = $vehicle_model->getFind($data['vehicle_id'], 'qr_code,number');
            @unlink('.' . $this->codePath . $vehicle_data['qr_code']);
            $code_url = $setting_data['scan_url'] . $vehicle_data['number'];
            $qr_code = $this->qrCode($code_url, $vehicle_data['number']);
            $data['qr_code'] = $qr_code;
            if (!$vehicle_model->operation($data, false)){
                $this->returnError($vehicle_model->getError());
            }
            $this->returnSuccess('保存成功');
        }
        $vehicle_id = input('param.vehicle_id', 0, 'intval');
        $oldData = [];
        if (!empty($vehicle_id)){
            $oldData = $vehicle_model->getFind($vehicle_id);
            $area_name = $area_model->getField($oldData['area_id'], 'area_name');
            $oldData['area_name'] = empty($area_name) ? '' : $area_name;
            $oldData['fixed_name'] = empty($fixed_name) ? '' : $fixed_name;
        }
        // 设备类型
        $type_id = empty($oldData['type_id']) ? 0 : intval($oldData['type_id']);
        $device_type = new \app\common\model\DeviceType();
        $type_list = $device_type->getList(['is_open'=>1]);
        if (!empty($type_list) && empty($type_id)){
            $type_id = $type_list['0']['type_id'];
        }

        View::assign([
            'type_id'=>$type_id,
            'type_list'=>$type_list,
            'oldData'=>$oldData
        ]);
    }

    public function batchInsert()
    {
        if (request()->isPost())
        {
            $data = input('post.');
            $type_id = floatval($data['type_id']);
            if (empty($type_id)){
                $this->returnError('请选择设备类型');
            }
            $number = floatval($data['number']);
            if (empty($number)){
                $this->returnError('请输入创建数量');
            }
            if ($number > 2000){
                $this->returnError('每次批量创建数量不能大于2000');
            }
            if ($number > 0){
                $area_data = [];
                $area_model = new \app\common\model\Area();
                if ($this->adminData['role_id'] == 1){
                    $area_id = floatval($data['area_id']);
                    if (!empty($area_id)){
                        $area_data = $area_model->getFind(['area_id'=>$area_id], 'area_id,admin_id,manager_id');
                    }
                }else{
                    $area_where['area_pid'] = ['neq', 0];
                    if ($this->adminData['level'] != 0){
                        $area_where['manager_id'] = $this->adminId;
                        if ($this->adminData['level'] == 1){
                            if ($this->adminData['role_id'] != 2){
                                $area_where['manager_id'] = $this->adminData['admin_pid'];
                            }
                        }
                    }
                    $area_data = $area_model->getFind($area_where, 'area_id,admin_id,manager_id');
                }
                $new_time = NEW_TIME;
                $data = [];
                $vehicle_number = '';
                $vehicle_model = new \app\common\model\Vehicle();
                for ($i = 0; $i < $number; $i++){
                    if (empty($vehicle_number)){
                        $vehicle_number = $vehicle_model->vehicleNumber($type_id);
                    }else{
                        $vehicle_number = $vehicle_model->vehicleNumber($type_id, $vehicle_number);
                    }
                    $data[] = array_merge(
                        [
                            'password'=>'123456',
                            'number'=>$vehicle_number,
                            'remark'=>'',
                            'create_time'=>$new_time,
                            'update_time'=>$new_time,
                            'last_time'=>$new_time,
                            'type_id'=>$type_id,
                            'state'=>2
                        ], $area_data
                    );
                }
                $rows = $vehicle_model->insertAll($data);
                if (empty($rows)){
                    $this->returnError('保存失败');
                }
                $this->returnSuccess('保存成功');
            }
        }
        // 设备类型
        $type_id = 0;
        $device_type = new \app\common\model\DeviceType();
        $type_list = $device_type->getList(['is_open'=>1]);
        if (!empty($type_list)){
            if (is_array($type_list)){
                foreach ($type_list as $key=>$val){
                    $type_id = $type_list['0']['type_id'];
                }
            }
        }

        View::assign([
            'type_list'=>$type_list
        ]);
        return View::fetch();
    }

    // 批量导入设备信息
    public function importVehicle()
    {
        if (request()->isPost())
        {
            $fixed_id = input('param.fixed_id', 0, 'intval');
            if (empty($fixed_id)){
                $this->returnError('请选择网点');
            }
            // Get the form upload file
            $file = request()->file('excel');
            $file_path = './static/upload/xls/';
            $time_path = date('Y/m/d/', time());
            $server_path = $file_path . $time_path;
            // Determine if the directory is created
            if(!is_dir($server_path)){
                mkdir($server_path, 0777, true);
            }
            $filename = uniqid();
            // Move to the frame application root directory /static/upload/ under the directory
            if($file){
                $info = $file->move($server_path, $filename);
                if(!$info){
                    $this->returnError($file->getError());
                }
                $filePath = $server_path . $info->getFilename();
                $device_data = $this->readExcel($filePath);
                $param = [];
                if (is_array($device_data)){
                    foreach ($device_data as $key=>$val){
                        if (!empty($val['2'])){
                            if ($key > 0){
                                $param[] = [
                                    'device'=>$val['0'] . '',
                                    'password'=>$val['0'] . '',
                                    'number'=>$val['0'] . '',
                                    'remark'=>$val['0'] . '',
                                ];
                            }
                        }
                    }
                }
                $new_data = [];
                $vehicle_model = new \app\common\model\Vehicle();
                $rows = $vehicle_model->insertAll($new_data);
                if (empty($rows)){
                    $this->returnError('保存失败');
                }
                $this->returnSuccess('保存成功');
            }
        }
        return View::fetch();
    }

    // 查看定位
    public function viewVehicle()
    {
        $vehicle_id = input('param.vehicle_id');
        if (empty($vehicle_id)){
            $this->returnError('查看实物');
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $data = $vehicle_model->getFind($vehicle_id);

        View::assign([
            'data'=>json_encode($data),
        ]);
        return View::fetch();
    }

    public function showVehicle()
    {
        $vehicle_id = input('param.vehicle_id');
        if (empty($vehicle_id)){
            $this->returnError('查看实物');
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $data = $vehicle_model->getFind($vehicle_id);

        View::assign([
            'data'=>json_encode($data),
        ]);
        return View::fetch();
    }

    // 速度设置
    public function speed()
    {
        $vehicle_id = input('param.vehicle_id', 0, 'intval');
        $vehicle_model = new \app\common\model\Vehicle();
        $max_speed = $vehicle_model->getField($vehicle_id, 'max_speed');
        if (request()->isPost())
        {
            $post_speed = input('post.max_speed', 0, 'intval');
            if (empty($vehicle_id)){
                $this->returnError('设置失败');
            }
            if ($max_speed == $post_speed){
                $this->returnError('无意义操作');
            }
            $vehicle_data = $vehicle_model->getFind($vehicle_id, 'device,type_id');
            if (empty($vehicle_data['device'])){
                $this->returnError('未绑定设备');
            }
            if ($vehicle_data['device'] == 3){
                $this->returnError('自行车系列无此项设置');
            }
            import('ego.DrGps');
            $ego = new \DrGps();
            $setting_model = new \app\common\model\Setting();
            $token = $setting_model->getToken();
            $rows = $ego->speed($vehicle_data['device'], $token, $post_speed);
            if (!$rows){
                $this->returnError('设置失败');
            }
            $rows = $vehicle_model->where('vehicle_id', $vehicle_id)->setField('max_speed', $post_speed);
            if (!$rows){
                $this->returnError('设置失败');
            }
            $this->returnSuccess('设置成功');
        }
        View::assign([
            'vehicle_id'=>$vehicle_id,
            'max_speed'=>empty($max_speed) ? 0 : $max_speed,
        ]);
        return View::fetch();
    }

    // audit
    public function auditVehicle()
    {
        $param = input('param.');
        if (empty($param['vehicle_id'])){
            $this->jsonReturn(0);
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $rows = $vehicle_model->vehicleStatus($param['vehicle_id'], 'state', 1, 2);
        if (empty($rows)){
            $this->jsonReturn(0);
        }
        $this->jsonReturn(1);
    }

    // delete
    public function deleteVehicle()
    {
        $param = input('param.');
        if (empty($param['vehicle_id'])){
            $this->returnError('删除失败');
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $rows = $vehicle_model->vehicleRemove($param['vehicle_id']);
        if (empty($rows)){
            $this->returnError('删除失败');
        }
        $this->returnSuccess('删除成功', url('Vehicle/index', ['p'=>$this->p]));
    }

    // recovered
    public function restoreVehicle()
    {
        $param = input('param.');
        if (empty($param['vehicle_id'])){
            $this->returnError('操作失败');
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $rows = $vehicle_model->vehicleStatus($param['vehicle_id'], 'status', 0, 4);
        if (empty($rows)){
            $this->returnError('操作失败');
        }
        $this->returnSuccess('操作成功', url('Vehicle/index', ['p'=>$this->p]));
    }

    // shift delete
    public function shiftDelete()
    {
        $param = input('param.');
        if (empty($param['vehicle_id'])){
            $this->returnError('删除失败');
        }
        $vehicle_model = new \app\common\model\Vehicle();
        $rows = $vehicle_model->vehicleRemove($param['vehicle_id']);
        if (empty($rows)){
            $this->returnError('删除失败');
        }
        $this->returnSuccess('删除成功', url('Vehicle/index', ['p'=>$this->p]));
    }

    // Batch import vehicle information format to download
    public function importExcel()
    {
        import("excel.PHPExcel");
        import("excel.PHPExcel.IOFactory");
        $filePath = getcwd() . '/static/upload/xls/import_vehicle.xlsx';
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename=import_excel.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    // create qr code
    public function vehicleCode()
    {
        $vehicle_model = new \app\common\model\Vehicle();
        $vehicle_data = $vehicle_model->getList(['state'=>2,'qr_code'=>'']);
        $setting_model = new \app\common\model\Setting();
        $setting_data = $setting_model->settingFind('site');
        if (empty($setting_data['scan_url'])){
            $this->returnError('请设置扫码下载地址');
        }
        if (!empty($vehicle_data)){
            if (is_array($vehicle_data)){
                foreach ($vehicle_data as $key=>$val){
                    // $code_data['number'] = $val['number'];
                    // $code_url = $setting_data['scan_url'] . '?' . urlencode(http_build_query($code_data));
                    $code_url = $setting_data['scan_url'] . $val['number'];
                    $qr_code = $this->qrCode($code_url, $val['number']);
                    $vehicle_model->where('vehicle_id', $val['vehicle_id'])->update(['qr_code'=>$qr_code]);
                }
            }
        }
        $this->returnSuccess('创建成功');
    }

    public function downloadImages()
    {
        $zip = new \ZipArchive();
        $filename = getcwd() . '/static/upload/download.zip';
        unlink($filename);
        $zip->open($filename, $zip::CREATE);

        $file_path = getcwd() . '/static/upload/code/' . date('Y/m/d/');

        $images = $this->scanDir($file_path);
        if (empty($images)){
            $this->returnError('没有可下载文件');
        }
        foreach ($images as $key => $value) {
            if ($key > 1){
                $zip->addFile($file_path . $value, $value);
            }
        }
        $zip->close();

        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachment; filename="'.basename($filename).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        readfile($filename);
        exit;
    }

    protected function scanDir($filepath){
        $file_array = [];
        if (is_dir($filepath)) {
            $file_array = scandir($filepath);
        }
        return $file_array;
    }

    // Create a read excel data that can be used for library entry
    protected function readExcel($path)
    {
        import("excel.PHPExcel");
        import("excel.PHPExcel.IOFactory");
        $type = 'Excel2007';
        $objReader = \PHPExcel_IOFactory::createReader($type);
        $objPHPExcel = \PHPExcel_IOFactory::load($path);
        /*$sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // Total number of rows
        $highestColumn = $sheet->getHighestColumn(); // Get the total number of columns*/
        $dataArray = $objPHPExcel->getSheet(0)->toArray();
        return $dataArray;
    }
}